package com.zhijian.medical.util;

import com.lowagie.text.DocumentException;
import com.lowagie.text.Element;
import com.lowagie.text.pdf.*;
import org.apache.commons.lang3.StringUtils;

import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

/**
 * Created by haocg on 2018/11/23.
 */
public class WaterMarkUtil {

    public static void main(String[] args) {
        File oldFile = new File("D:\\data\\pdf\\test1.pdf");
        File newFile = new File("D:\\data\\pdf\\test5.pdf");
        try {
            setWatermark(oldFile.getAbsolutePath(), newFile.getAbsolutePath(), "受控文件", "生效日期：2023年08月24日", "FZ-SOP-E-003-02-20230723-1");
        } catch (Exception e) {

        }
    }

    /**
     * @param
     * @param input 原PDF位置
     * @param s1    页脚添加水印
     * @throws DocumentException
     * @throws IOException
     */
    public static void setWatermark(String input, String outputFile, String s1, String s2, String s3)
            throws DocumentException, IOException, NoSuchFieldException, IllegalAccessException {
        PdfReader reader = new PdfReader(input);
        java.lang.reflect.Field f = reader.getClass().getDeclaredField(
                "encrypted");
        f.setAccessible(true);
        f.set(reader, false);
        PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(
                outputFile));
        int total = reader.getNumberOfPages() + 1;
        PdfContentByte content;
        BaseFont base = BaseFont.createFont("/usr/local/upload/store/firmware/simsun.ttc,1", BaseFont.IDENTITY_H, false);
        PdfGState gs = new PdfGState();
        float pageWidth = 0;
        float pageHeight = 0;
        for (int i = 1; i < total; i++) {
            pageWidth = reader.getPageSize(i).getWidth();
            pageHeight = reader.getPageSize(i).getHeight();
            content = stamper.getOverContent(i);// 在内容上方加水印
            // content = stamper.getUnderContent(i);//在内容下方加水印

            float v = pageHeight / 2;
            gs.setFillOpacity(0.9f);
            content.setGState(gs);
            content.beginText();
            content.setColorFill(Color.LIGHT_GRAY);
            content.setFontAndSize(base, 30);
            content.setTextMatrix(70, 200);
//            content.showTextAligned(Element.ALIGN_CENTER, "仅供江苏号百公司使用，请勿外传", 200, 320, 35);
//            content.showTextAligned(Element.ALIGN_CENTER, waterMarkName, 350, 180, 35);
            content.showTextAligned(Element.ALIGN_CENTER, s1, pageWidth / 2, v, 35);
            content.endText();

            //2
            content = stamper.getOverContent(i);// 在内容上方加水印
            // content = stamper.getUnderContent(i);//在内容下方加水印
            gs.setFillOpacity(0.9f);
            content.setGState(gs);
            content.beginText();
            content.setColorFill(Color.LIGHT_GRAY);
            content.setFontAndSize(base, 20);
            content.setTextMatrix(70, 200);
//            content.showTextAligned(Element.ALIGN_CENTER, "仅供江苏号百公司使用，请勿外传", 200, 320, 35);
//            content.showTextAligned(Element.ALIGN_CENTER, waterMarkName, 350, 180, 35);
            content.showTextAligned(Element.ALIGN_CENTER, s2, pageWidth / 2, v - 40, 35);
            content.endText();

            //3
            if (StringUtils.isNotBlank(s3)){
                content = stamper.getOverContent(i);// 在内容上方加水印
                // content = stamper.getUnderContent(i);//在内容下方加水印
                gs.setFillOpacity(0.9f);
                content.setGState(gs);
                content.beginText();
                content.setColorFill(Color.LIGHT_GRAY);
                content.setFontAndSize(base, 20);
                content.setTextMatrix(70, 200);
//            content.showTextAligned(Element.ALIGN_CENTER, "仅供江苏号百公司使用，请勿外传", 200, 320, 35);
//            content.showTextAligned(Element.ALIGN_CENTER, waterMarkName, 350, 180, 35);
                content.showTextAligned(Element.ALIGN_CENTER, s3, pageWidth / 2, v - 80, 35);
                content.endText();
            }


        }
        stamper.close();
        reader.close();
    }

    public static void setWatermarkV2(String inputFile, String outputFile, String waterMarkName) {
        int interval = -5;
        try {
            PdfReader reader = new PdfReader(inputFile);
            java.lang.reflect.Field f = reader.getClass().getDeclaredField(
                    "encrypted");
            f.setAccessible(true);
            f.set(reader, false);
            PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(
                    outputFile));

            BaseFont base = BaseFont.createFont("simsun.ttc,1", BaseFont.IDENTITY_H, false);

            com.lowagie.text.Rectangle pageRect = null;
            PdfGState gs = new PdfGState();
            gs.setFillOpacity(0.26f);
            gs.setStrokeOpacity(0.4f);
            double total = reader.getNumberOfPages() + 1;

            JLabel label = new JLabel();
            FontMetrics metrics;
            double textH = 0;
            double textW = 0;
            label.setText(waterMarkName);
            metrics = label.getFontMetrics(label.getFont());
            textH = metrics.getHeight();
            textW = metrics.stringWidth(label.getText());

            PdfContentByte under;
            for (int i = 1; i < total; i++) {

                pageRect = reader.getPageSizeWithRotation(i);
                under = stamper.getOverContent(i);
                under.saveState();
                under.setGState(gs);
                under.beginText();
                under.setFontAndSize(base, 10);

                // 水印文字成30度角倾斜
                //你可以随心所欲的改你自己想要的角度
                for (double height = interval + textH; height < pageRect.getHeight(); height = height + textH * 5) {
                    for (double width = interval + textW; width < pageRect.getWidth() + textW; width = width + textW / 1.5) {
                        double a = width - textW;
                        double b = height - textH;
                        under.showTextAligned(Element.ALIGN_MIDDLE, waterMarkName, (float) a, (float) b, 30);
                    }
                }
                // 添加水印文字
                under.endText();
            }
            //说三遍
            //一定不要忘记关闭流
            //一定不要忘记关闭流
            //一定不要忘记关闭流
            stamper.close();
            reader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static void readZipFileV2(String inputFileName, String outputFile, String waterMarkName) throws Exception {
        ZipFile zf = new ZipFile(inputFileName);

        InputStream in = new BufferedInputStream(new FileInputStream(inputFileName));
        ZipInputStream zin = new ZipInputStream(in);

        ZipEntry ze;

        File fileOut = new File(outputFile);//指定输出位置
        FileOutputStream fileOutputStream = new FileOutputStream(fileOut);//以流的形式输出
        ZipOutputStream zipOut = new ZipOutputStream(fileOutputStream);//注入到Zip中，以Zip的形式输出
        while ((ze = zin.getNextEntry()) != null) {
            if (ze.isDirectory()) {
            } else {
                System.err.println("file - " + ze.getName() + " : "
                        + ze.getSize() + " bytes");
                long size = ze.getSize();
                if (size > 0) {

                    String fileName = ze.getName();
                    if (fileName.endsWith(".pdf")) {
                        int interval = -5;
                        try {
                            PdfReader reader = new PdfReader(zf.getInputStream(ze));
                            java.lang.reflect.Field f = reader.getClass().getDeclaredField(
                                    "encrypted");
                            f.setAccessible(true);
                            f.set(reader, false);

                            PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(fileName));

                            BaseFont base = BaseFont.createFont("simsun.ttc,1", BaseFont.IDENTITY_H, false);

                            com.lowagie.text.Rectangle pageRect = null;
                            PdfGState gs = new PdfGState();
                            gs.setFillOpacity(0.26f);
                            gs.setStrokeOpacity(0.4f);
                            double total = reader.getNumberOfPages() + 1;

                            JLabel label = new JLabel();
                            FontMetrics metrics;
                            double textH = 0;
                            double textW = 0;
                            label.setText(waterMarkName);
                            metrics = label.getFontMetrics(label.getFont());
                            textH = metrics.getHeight();
                            textW = metrics.stringWidth(label.getText());

                            PdfContentByte under;
                            for (int i = 1; i < total; i++) {

                                pageRect = reader.getPageSizeWithRotation(i);
                                under = stamper.getOverContent(i);
                                under.saveState();
                                under.setGState(gs);
                                under.beginText();
                                under.setFontAndSize(base, 10);

                                // 水印文字成30度角倾斜
                                //你可以随心所欲的改你自己想要的角度
                                for (double height = interval + textH; height < pageRect.getHeight(); height = height + textH * 5) {
                                    for (double width = interval + textW; width < pageRect.getWidth() + textW; width = width + textW / 1.5) {
                                        double a = width - textW;
                                        double b = height - textH;
                                        under.showTextAligned(Element.ALIGN_MIDDLE, waterMarkName, (float) a, (float) b, 30);
                                    }
                                }
                                // 添加水印文字
                                under.endText();
                            }
                            //说三遍
                            //一定不要忘记关闭流
                            //一定不要忘记关闭流
                            //一定不要忘记关闭流
                            stamper.close();
                            reader.close();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }


                    File inputFile = new File(fileName);
                    FileInputStream fileInputStream = new FileInputStream(inputFile);
                    byte[] inOutByte = new byte[fileInputStream.available()];
                    fileInputStream.read(inOutByte);


                    //在压缩文件中创建文件实体
                    ZipEntry entry = new ZipEntry(fileName);
                    zipOut.putNextEntry(entry);
                    //将数组中的数据注入到ZipOutputStream中
                    zipOut.write(inOutByte);
                    //关闭流
                    fileInputStream.close();

                }
//                System.out.println();
            }

        }
        zipOut.closeEntry();
        zipOut.close();
        fileOutputStream.close();
        zin.closeEntry();
    }


    public static void readZipFile(String inputFileName, String outputFile, String waterMarkName) throws Exception {
        ZipFile zf = new ZipFile(inputFileName);

        InputStream in = new BufferedInputStream(new FileInputStream(inputFileName));
        ZipInputStream zin = new ZipInputStream(in);

        ZipEntry ze;

        File fileOut = new File(outputFile);//指定输出位置
        FileOutputStream fileOutputStream = new FileOutputStream(fileOut);//以流的形式输出
        ZipOutputStream zipOut = new ZipOutputStream(fileOutputStream);//注入到Zip中，以Zip的形式输出
        while ((ze = zin.getNextEntry()) != null) {
            if (ze.isDirectory()) {
            } else {
                System.err.println("file - " + ze.getName() + " : "
                        + ze.getSize() + " bytes");
                long size = ze.getSize();
                if (size > 0) {

                    String fileName = ze.getName();
                    if (fileName.endsWith(".pdf")) {
                        PdfReader reader = new PdfReader(zf.getInputStream(ze));
                        java.lang.reflect.Field f = reader.getClass().getDeclaredField(
                                "encrypted");
                        f.setAccessible(true);
                        f.set(reader, false);
                        PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(
                                fileName));
                        int total = reader.getNumberOfPages() + 1;
                        PdfContentByte content;
                        BaseFont base = BaseFont.createFont("simsun.ttc,1", BaseFont.IDENTITY_H, false);
                        PdfGState gs = new PdfGState();
                        float pageWidth = 0;
                        float pageHeight = 0;
                        for (int i = 1; i < total; i++) {
                            pageWidth = reader.getPageSize(i).getWidth();
                            pageHeight = reader.getPageSize(i).getHeight();
                            content = stamper.getOverContent(i);// 在内容上方加水印
                            // content = stamper.getUnderContent(i);//在内容下方加水印
                            gs.setFillOpacity(0.2f);
                            // content.setGState(gs);
                            content.beginText();
                            content.setColorFill(Color.LIGHT_GRAY);
                            content.setFontAndSize(base, 30);
                            content.setTextMatrix(70, 200);
//            content.showTextAligned(Element.ALIGN_CENTER, "仅供江苏号百公司使用，请勿外传", 200, 320, 35);
//            content.showTextAligned(Element.ALIGN_CENTER, waterMarkName, 350, 180, 35);
                            content.showTextAligned(Element.ALIGN_CENTER, waterMarkName, pageWidth / 2, pageHeight / 2, 35);
                            content.endText();
                        }
                        stamper.close();
                        reader.close();
                    }


                    File inputFile = new File(fileName);
                    FileInputStream fileInputStream = new FileInputStream(inputFile);
                    byte[] inOutByte = new byte[fileInputStream.available()];
                    fileInputStream.read(inOutByte);


                    //在压缩文件中创建文件实体
                    ZipEntry entry = new ZipEntry(fileName);
                    zipOut.putNextEntry(entry);
                    //将数组中的数据注入到ZipOutputStream中
                    zipOut.write(inOutByte);
                    //关闭流
                    fileInputStream.close();

                }
//                System.out.println();
            }

        }
        zipOut.closeEntry();
        zipOut.close();
        fileOutputStream.close();
        zin.closeEntry();
    }
}
